var express = require('express');
var router = express.Router();
var {
  User
} = require('../database/models'); // 引入模型
var qr = require('qr-image') //二维码生成插件
// var utils = require('../common/utils');
var token = require('../common/token');
var async = require('async');
/* GET users listing. */
var request = require('request');
router.all('/', function (req, res) {
  res.send({
    title: 'Express',
    content: '欢迎访问Express'
  })
})
router.all('/getAutoResult', async function (req, res) {
  const code = req.body.code || req.query.code;
  const appid = 'wx2c08c0856a3dca51';
  const secret = '9732f249f1d5d127a824acb5f7ef03cf';
  const url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appid}&secret=${secret}&code=${code}&grant_type=authorization_code`
  const opts = {
    url,
  }

  const getAccessToken = function () {
    return new Promise((resolve, reject) => {
      request(opts, (err, data) => {
        if (err) reject(err);
        resolve(data)
      })
    })
  }
  const getUserInfo = function (uinfo) {
    return new Promise((resolve, reject) => {
      request(uinfo, (err, data) => {
        if (err) reject(err);
        resolve(data)
      })
    })
  }
  const result = await getAccessToken();
  if (JSON.parse(result.body) && JSON.parse(result.body).openid) {
    const {
      access_token,
      openid
    } = JSON.parse(result.body);
    const opt = {
      url: `https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}&lang=zh_CN`
    };
    const ui = await getUserInfo(opt);
    const uinfo = JSON.parse(ui.body)
    console.log('uinfo', uinfo);
    uinfo.openid = openid;
    uinfo.avatarUrl=uinfo.headimgurl?uinfo.headimgurl:'';
    User.findOne({
      openid
    }, (err, data) => {
      if (err) return false;
      if (data) {
        res.cookie('openid',openid);
        res.redirect(302, `https://www.yteris.com/h5?openid=${openid}`)
      } else {
        User.create(uinfo, (err, data) => {
          if (err) throw new Error(err);
          res.redirect(302, `https://www.yteris.com?openid=${openid}`)
        })
      }
    })

  } else {
    await res.redirect(302, `https://www.yteris.com`)
  }

})
router.all('/auto', function (req, res) {
  //const code = req.body.code || req.query.code;
  const appid = 'wx2c08c0856a3dca51';
  const redirect_url = 'https://www.yteris.com/v2/index/getAutoResult';
  const state = 'helloworld';
  const scope = 'snsapi_userinfo';
  //const scope='snsapi_base';
  const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_url}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`
  res.redirect(302, url);
})
router.all('/register', function (req, res) {
   const openid = req.body.openid;
   User.update({openid},req.body,(err,data)=>{
       if(err) throw new Error('更新用户信息失败:' + err);
       if(data){
        res.send({
          msg:'注册成功',
          status:4,
          data:data
        })
       }else{
        res.send({
          msg:'注册失败',
          status:3,
          data:[],
        })
       }
      
   })
})
router.post('/getToken', function (req, res) {
  let login = req.body;
  let a = token.createToken(login, 100)
  console.log(a);
  res.send({
    msg: '请求成功',
    data: {
      token: a
    },
    code: 3
  })
})
router.post('/checkTokens', function (req, res) {
  console.log(req.body);
  let tokens = req.body.token;
  let a = token.checkToken(tokens)
  console.log(a);
})
router.post('/login', function (req, res) {
  console.log(req.body.username);
  var username = req.body.username;
  var pwd = req.body.password;
  console.log(pwd);
  var role = {
    'username': username,
    'password': pwd
  };
  var name = {
    'username': username
  };
  User.findOne(role, (err, data) => {
    if (err) return console.log('登录异常');
    console.log(data);
    if (data && data.username == username && data.password == pwd) {
      res.send({
        code: 4,
        msg: '登录成功',
      })
    } else {
      res.send({
        code: 3,
        msg: '登录失败',
      })
    }
  })
});
//历史上的今天
router.post('/history_today', (req, res) => {
  var time = new Date();
  var mm = time.getMonth() + 1;
  var dd = time.getDate();
  var date = mm + '/' + dd;
  console.log(date);
  var key = '402fbd2769a4c03cdfb6009c09ce4b49';
  let opt = {
    url: `http://v.juhe.cn/todayOnhistory/queryEvent.php?key=${key}&date=${date}`
  }
  request(opt, (err, resp, data) => {
    if (err) return console.log('request fail');
    if (resp.statusCode == '200') {

      res.send({
        data: JSON.parse(data),
        status: 3,
        msg: '请求成功',
      })
    } else {
      res.send({
        status: 4,
        msg: '请求失败',
        data: {}
      })
    }
  })
})
//获取彩票种类
router.post('/getlottery', function (req, res) {
  var opt = {
    url: `http://api.jisuapi.com/caipiao/class?appkey=21fab4ec01fd7220`
  }
  request(opt, (err, resp, data) => {
    if (err) return console.log('请求失败');
    console.log(resp.statusCode);
    var sort = JSON.parse(data);
    //var a=sort.result.splice(0,18)
    //sort.result=a;
    res.send({
      data: sort
    })
  })
});
//按彩票种类查询
router.post('/lotteryfound', function (req, res) {
  var caipiaoid = req.body.cid;
  var issueno = req.body.ino;
  var opt = {
    url: `http://api.jisuapi.com/caipiao/query?appkey=21fab4ec01fd7220&caipiaoid=${caipiaoid}&issueno=${issueno}`
    //http://api.jisuapi.com/caipiao/query?appkey=yourappkey&caipiaoid=13&issueno=
    //http://api.jisuapi.com/caipiao/history?appkey=yourappkey&caipiaoid=13&issueno=&start=0&num=10
  }
  console.log(opt);
  request(opt, (err, resp, data) => {
    if (err) return console.log('请求失败');
    console.log(resp.statusCode);
    var sort = JSON.parse(data);
    console.log(sort);
    res.send({
      data: sort
    })
  })
})

//某一种彩票当期详细查询
router.post('/lotteryhistory', function (req, res) {
  var caipiaoid = req.body.cid;
  console.log(caipiaoid);
  var opt = {
    url: `http://api.jisuapi.com/caipiao/history?appkey=21fab4ec01fd7220&caipiaoid=${caipiaoid}&issueno=&start=&num=10`
    //http://api.jisuapi.com/caipiao/query?appkey=yourappkey&caipiaoid=13&issueno=
    //http://api.jisuapi.com/caipiao/history?appkey=yourappkey&caipiaoid=13&issueno=&start=0&num=10
    //http://api.jisuapi.com/caipiao/history?appkey=21fab4ec01fd7220&caipiaoid=13&issueno=&start=&num=10
  }
  request(opt, (err, resp, data) => {
    if (err) return console.log('请求失败');
    console.log(resp.statusCode);
    var sort = JSON.parse(data);

    console.log(sort);
    res.send({
      data: sort
    })
  })
})
//星座查询列表
router.post('/constellationList', function (req, res) {
  var opt = {
    url: `http://api.jisuapi.com/astro/all?appkey=21fab4ec01fd7220`
    //http://api.jisuapi.com/caipiao/query?appkey=yourappkey&caipiaoid=13&issueno=
    //http://api.jisuapi.com/caipiao/history?appkey=yourappkey&caipiaoid=13&issueno=&start=0&num=10
    //http://api.jisuapi.com/caipiao/history?appkey=21fab4ec01fd7220&caipiaoid=13&issueno=&start=&num=10
  }
  request(opt, (err, resp, data) => {
    if (err) return console.log('请求失败');
    console.log(resp.statusCode);
    var sort = JSON.parse(data);

    console.log(sort);
    res.send({
      data: sort
    })
  })
})
router.post('/constellationDetail', function (req, res) {
  var time = new Date();
  var yy = time.getFullYear()
  var mm = (time.getMonth() + 1) < 10 ? '0' + (time.getMonth() + 1) : (time.getMonth() + 1);
  var dd = time.getDate() < 10 ? '0' + time.getDate() : time.getDate();
  var date = yy + '-' + mm + '-' + dd;
  var cid = req.body.cid;
  console.log(date);
  console.log(cid);
  var opt = {
    url: `http://api.jisuapi.com/astro/fortune?astroid=${cid}&date=${date}&appkey=21fab4ec01fd7220`
    //http://api.jisuapi.com/caipiao/query?appkey=yourappkey&caipiaoid=13&issueno=
    //http://api.jisuapi.com/caipiao/history?appkey=yourappkey&caipiaoid=13&issueno=&start=0&num=10
    //http://api.jisuapi.com/caipiao/history?appkey=21fab4ec01fd7220&caipiaoid=13&issueno=&start=&num=10
  }
  request(opt, (err, resp, data) => {
    if (err) return console.log('请求失败');
    console.log(resp.statusCode);
    var sort = JSON.parse(data);

    console.log(sort);
    res.send({
      data: sort
    })
  })
})

router.get('/create_qrcode', function (req, res, next) {

  var text = req.query.text;
  var text1 = '1111111';
  console.log('text1', text1)
  console.log(text)
  try {
    var img = qr.image(text);

    res.writeHead(200, {
      'Content-Type': 'image/png'
    });

    img.pipe(res);
    console.log(res)

  } catch (e) {

    res.writeHead(414, {
      'Content-Type': 'text/html'
    });

    res.end('<h1>414 Request-URI Too Large</h1>');

  }

})


router.all('/new_qrcode1', function (req, res, next) {
  res.send('haode')
})
//水印二维码
// router.all('/new_qrcode', function (req, res, next) {
//   var task1 = function (callback) {
//     var url = 'http://www.baidu.com';
//     utils.createQr(url, function (err, data) {
//       if (err) {
//         console.log(err);
//         callback(err, null);
//         return;
//       }
//       callback(null, data);
//     })
//   };

//   var task2 = function (waterImg, callback) {
//     //原图
//     var sourceImg = 'E:/project/vueproject/own_manage/public/image/1.jpg';
//     utils.addWater(sourceImg, waterImg, function (data) {
//       callback(null, data);
//     })
//   };

//   async.waterfall([task1, task2], function (err, result) {
//     if (err) {
//       console.log(err);
//       return;
//     }
//     console.log(result);
//     res.send(result)
//   })

// })
router.all('/new_all_house', function (req, res) {

})

module.exports = router;